<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <title>冲印设置</title>
    <link href="../css.min/mui.min.css" rel="stylesheet"/>
    <link rel="stylesheet" href="../css/iconfont.css" />
    <link rel="stylesheet" href="../css/header.css" />
    <link rel="stylesheet" href="../css/common.css" />
    <style>
    	.print-btn{
    		background-color:#EE4B62;
    		color: white !important;
    	}
    	.select-card{
    		margin-top: 10px;
    		margin-bottom: 10px;
    	}
    	.mui-table-view .mui-table-view-divider{
    		color:#FFFFFF;
    		font-weight: bold;
    		background-color: #56abe4;
    	}
    	.dlist {
			padding: 0px;
			margin: 1em;
			background: #fff;
			border: 1px solid #ddd;
			-webkit-border-radius: 3px;
			border-radius: 3px;
		}
		.ditem {
			overflow: hidden;
			list-style-type: none;
			font-size: 1em;
			padding: 1em;
			border-bottom: inset 1px #ebebeb;
			vertical-align: middle;
		}
		.ditem:active {
			background: #f4f4f4;
		}
		.ditem:last-child {
			border-bottom: inset 0px #ebebeb;
		}
		.ditem-empty {
			overflow: hidden;
			list-style-type: none;
			font-size: 1em;
			padding: 1em;
			vertical-align: middle;
		}
		.get-photo{
			margin-right: 30px;
			color: #FFFFFF;
			font-size: 30px;
		}
		.photo-name{
			color: black;
		}
		.imgpreview-close{
			font-size: 30px;
		}
		.mui-scroll-wrapper{
			bottom: 50px;
		}
    </style>
</head>
<body>
	<header class="mui-bar mui-bar-nav">
	    <a class="mui-action-back mui-icon mui-icon-close mui-pull-left"></a>
	    <h1 class="mui-title">冲印设置</h1>
	</header>
	<div class="mui-content mui-scroll-wrapper">
		<div class="mui-scroll">
			<ul class="mui-table-view mui-table-view-striped mui-table-view-condensed">
				<li class="mui-table-view-divider" style="height: 40px;line-height: 40px;">				
					<a id="camera" class="get-photo mui-icon iconfont icon-icon38  mui-pull-right"></a>
					<a id="gallery" class="get-photo mui-icon iconfont icon-see-photo mui-pull-right"></a>
				</li>
				
				<div class="mui-card select-card">
					<ul id="history" class="mui-table-view">
						<li id="empty" class="ditem-empty">请选择要冲印的照片</li>
						<!--<li class="mui-table-view-cell mui-media mui-disabled">
							<div class="mui-table">
								<div class="mui-table-cell mui-col-xs-8">
									<img class="mui-media-object mui-pull-left" src="../img/background.jpg">
									<div class="mui-media-body mui-h5 photo-name mui-ellipsis-2">
										幸福
									</div>
								</div>
								<div class="mui-table-cell mui-col-xs-4 mui-text-right">
									<a class="imgpreview-close mui-icon mui-icon-closeempty"></a>
								</div>
							</div>
						</li>-->
					</ul>
				</div>
				
				<li class="mui-table-view-divider">尺寸</li>
				<div class="mui-card select-card">
					<ul id="selected-size" class="mui-table-view mui-table-view-radio">
						<li class="mui-table-view-cell">
							<a class="mui-navigate-right">
								3寸（8.9cm×6.35cm）
							</a>
						</li>
						<li class="mui-table-view-cell mui-selected">
							<a class="mui-navigate-right">
								4寸（10.2cm×7.6cm）
							</a>
						</li>
						<li class="mui-table-view-cell">
							<a class="mui-navigate-right">
								5寸（12.7cm×8.9cm）
							</a>
						</li>
						<li class="mui-table-view-cell">
							<a class="mui-navigate-right">
								6寸（15.2cm×10.2cm）
							</a>
						</li>
						<li class="mui-table-view-cell">
							<a class="mui-navigate-right">
								7寸（17.8cm×12.7cm）
							</a>
						</li>
					</ul>
				</div>
				
				<li class="mui-table-view-divider">相纸</li>
				<div class="mui-card select-card">
					<ul id="selected-papertype" class="mui-table-view mui-table-view-radio">
						<li class="mui-table-view-cell mui-selected">
							<a class="mui-navigate-right">
								柯达Kodak
							</a>
						</li>
						<li class="mui-table-view-cell">
							<a class="mui-navigate-right">
								佳能Canon
							</a>
						</li>
						<li class="mui-table-view-cell">
							<a class="mui-navigate-right">
								爱普生EPSON
							</a>
						</li>
					</ul>
				</div>
				<li class="mui-table-view-divider" style="background-color: #FFFFFF;"></li>
			</ul>
		</div>
	</div>
	<nav id="nav" class="mui-bar mui-bar-tab">
		<a id="confirmPrint" class="mui-tab-item print-btn">开始冲印</a>
	</nav>
</body>
<script src="../js.min/mui.min.js"></script>
<script type="text/javascript" src="../js/config.js" ></script>
<script type="text/javascript" src="../js/utils.js" ></script>
<script type="text/javascript" src="../js.min/plupload.full.min.js" ></script>
<script type="text/javascript" src="../js.min/qiniu.min.js" ></script>
<script type="text/javascript" charset="utf-8">
    mui.init();
    
    var M=this;
    M.PhotoFiles=[];//已选照片
    
    /**
     * div scroll init
     */
    //阻尼系数
	var deceleration = mui.os.ios?0.003:0.0009;
	mui('.mui-scroll-wrapper').scroll({
		bounce: false,
		indicators: true, //是否显示滚动条
		deceleration:deceleration
	});
	
	/**
	 * 监听DOMContentLoaded事件
	 */
	var SelectedSizeDOM=null,SelectedPaperDOM=null,EmpryDOM=null,
	CameraDOM=null,GalleryDOM=null,HistoryDOM=null,ConfirmPrintDOM;
	document.addEventListener("DOMContentLoaded",function(){
		//获取DOM元素对象
		HistoryDOM=document.getElementById("history");
		SelectedSizeDOM=document.getElementById("selected-size");
		SelectedPaperDOM=document.getElementById("selected-papertype");
		EmpryDOM=document.getElementById("empty");
		CameraDOM=document.getElementById("camera");
		GalleryDOM=document.getElementById("gallery");
		ConfirmPrintDOM=document.getElementById("confirmPrint");
		
		/**
		 * 选择尺寸
		 */
		SelectedSizeDOM.addEventListener('selected',function(e){
			//"当前选中的为："+e.detail.el.innerText;
		});
		
		/**
		 * 选择相纸
		 */
		SelectedPaperDOM.addEventListener('selected',function(e){
			//"当前选中的为："+e.detail.el.innerText;
		});
		
		/**
		 * 拍照
		 */
		CameraDOM.addEventListener('tap',function(e){
			getImage();
		});
		
		/**
		 * 相册选取，支持多选
		 */
		GalleryDOM.addEventListener('tap',function(e){
			galleryImgs();
		});
		
		/**
		 * 开始冲印
		 */
		ConfirmPrintDOM.addEventListener('tap',function(e){
			var me=this;
			M.waiting=plus.nativeUI.showWaiting("准备中...");
			mui.ajax_query("getToken!PPH",{},function(d){
				
				if(!d) return M.waiting.close();
				if(!d.code || d.code!=100) return M.waiting.close();
				
				//init uploader
				me.uploader=d.token && initUploader(d.token);
				
				// addfile 
				if(M.PhotoFiles){
					for (var i = 0; i < M.PhotoFiles.length; i++) {
						me.uploader.addFile(me.uploader.File,M.PhotoFiles[i]); 
					}
				}
				
				mui.log("PhotoFiles:"+JSON.stringify(M.PhotoFiles));
				mui.log("start uploading...");
				M.waiting.close();
				
				//start uploading
				mui.log(me.uploader.hasOwnProperty("start")?"存在":"不存在");
				me.uploader.start();
				
			},function(c,m){
				M.waiting.close();
			});
		});
		
	},false );
	
	/**
	 * init uploader
	 */
	function initUploader(_uptoken){
		var uploader = Qiniu.uploader({
		    runtimes: 'html5,flash,html4',    //上传模式,依次退化
		    browse_button:'pickfiles',       //上传选择的点选按钮，**必需**
		    //uptoken_url: '/token',
		    //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
		    uptoken : _uptoken,
		    //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
		    // unique_names: true,
		    // 默认 false，key为文件名。若开启该选项，SDK会为每个文件自动生成key（文件名）
		    // save_key: true,
		        // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
		    domain: '7xp9yg.com1.z0.glb.clouddn.com',
		        //bucket 域名，下载资源时用到，**必需**
		    //container: 'container',           //上传区域DOM ID，默认是browser_button的父元素，
		    max_file_size: '100mb',           //最大文件体积限制
		    flash_swf_url: '../media/Moxie.swf',  //引入flash,相对路径
		    max_retries: 3,                   //上传失败最大重试次数
		    dragdrop: false,                   //开启可拖曳上传
		    //drop_element: 'container',        //拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
		    chunk_size: '4mb',                //分块上传时，每片的体积
		    auto_start: false,                 //选择文件后自动上传，若关闭需要自己绑定事件触发上传
		    init: {
		        'FilesAdded': function(up, files) {
		            plupload.each(files, function(file) {
		                // 文件添加进队列后,处理相关的事情
		                mui.alert("文件添加进队列");
		            });
		        },
		        'BeforeUpload': function(up, file) {
		               // 每个文件上传前,处理相关的事情
		               mui.alert("每个文件上传前,处理相关的事情");
		        },
		        'UploadProgress': function(up, file) {
		               // 每个文件上传时,处理相关的事情
		               mui.alert("每个文件上传时,处理相关的事情");
		        },
		        'FileUploaded': function(up, file, info) {
		        	   M.waiting.close();
		        	   mui.alert("上传成功");
		               // 每个文件上传成功后,处理相关的事情
		               // 其中 info 是文件上传成功后，服务端返回的json，形式如
		               // {
		               //    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
		               //    "key": "gogopher.jpg"
		               //  }
		               // 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
		               // var domain = up.getOption('domain');
		               // var res = parseJSON(info);
		               // var sourceLink = domain + res.key; 获取上传成功后的文件的Url
		        },
		        'Error': function(up, err, errTip) {
		               //上传出错时,处理相关的事情
		               M.waiting.close();
		        	   mui.alert("上传出错");
		        },
		        'UploadComplete': function() {
		               //队列文件处理完毕后,处理相关的事情
		               mui.alert("队列文件处理完毕后,处理相关的事情");
		        },
		        'Key': function(up, file) {
		            // 若想在前端对每个文件的key进行个性化处理，可以配置该函数
		            // 该配置必须要在 unique_names: false , save_key: false 时才生效
		            var key = "";
		            // do something with key here
		            return key
		        }
		    }
		});
		
		return uploader;
		// domain 为七牛空间（bucket)对应的域名，选择某个空间后，可通过"空间设置->基本设置->域名设置"查看获取
		// uploader 为一个plupload对象，继承了所有plupload的方法，参考http://plupload.com/docs
	}
	
	//拍照
	function getImage() {
		//outSet( "开始拍照：" );
		var cmr = plus.camera.getCamera();
		cmr.captureImage( function ( p ) {
			//outLine( "成功："+p );
			plus.io.resolveLocalFileSystemURL( p, function ( entry ) {
				createItem(entry.toLocalURL());
			}, function ( e ) {
				//outLine( "读取拍照文件错误："+e.message );
			} );
		}, function ( e ) {
			//outLine( "失败："+e.message );
		}, {filename:"_doc/camera/",index:1} );
	}
	
	function galleryImgs(){
		// 从相册中选择图片
		//outSet("从相册中选择多张图片:");
	    plus.gallery.pick( function(e){
	    	for(var i in e.files){
		    	createItem(e.files[i]);
	    	}
	    }, function ( e ) {
	    	//outSet( "取消选择图片" );
	    },{filter:"image",multiple:true});
	}
	
	//添加照片项
	function createItem(imgsrc) {
		var e=this;
		
		var li = document.createElement("li");
		li.className = "mui-table-view-cell mui-media mui-disabled";
		
		var tb=document.createElement("div");
		tb.className="mui-table";
		
		var cell8=document.createElement("div");
		cell8.className="mui-table-cell mui-col-xs-8";
		var img=document.createElement("img");
		img.className="mui-media-object mui-pull-left";
		img.src=imgsrc;
		img.setAttribute( "onclick", "displayFile(this);" );
		var pname=document.createElement("div");
		pname.className="mui-media-body mui-h5 photo-name mui-ellipsis-2";
		e.srcArray=imgsrc.split("/");
		pname.innerHTML=e.srcArray[e.srcArray.length-1];
		cell8.appendChild(img);
		cell8.appendChild(pname);
		
		var cell4=document.createElement("div");
		cell4.className="mui-table-cell mui-col-xs-4 mui-text-right";
		var deleteItem=document.createElement("a");
		deleteItem.className="imgpreview-close mui-icon mui-icon-closeempty";
		deleteItem.parentObj=li;
		deleteItem.setAttribute("onclick","removeImageItem(this);");
		cell4.appendChild(deleteItem);
		
		tb.appendChild(cell8);
		tb.appendChild(cell4);
		
		li.appendChild(tb);
		
		HistoryDOM.insertBefore(li, EmpryDOM.nextSibling);
		
		//已选照片
		M.PhotoFiles.push(imgsrc);
		
		// 设置空项不可见
		EmpryDOM.style.display = "none";
	}
	
	//查看图片
	var w=null;
	function displayFile(a) {
		if ( w ) {
			//outLine( "重复点击！" );
			return;
		}
		if ( !a || !a.src ) {
			//ouSet( "无效的媒体文件" );
			return;
		}
		
		w=plus.webview.create("image_preview.html","image_preview",
		{hardwareAccelerated:true,scrollIndicator:'none',scalable:true,bounce:"all",zindex:11});
		//w=utils.openWindow("image_preview","image_preview.html","pop-in",300,false);
		w.addEventListener( "loaded", function(){
			w.evalJS( "loadMedia('"+a.src+"')" );
		}, false );
		w.addEventListener( "close", function() {
			w = null;
		}, false );
		
		w.show( "fade-in" );
	}
	
	/**
	 * 删除已选择图片
	 */
	function removeImageItem(obj){
		HistoryDOM&&(HistoryDOM.removeChild(obj.parentObj));
		
		if(HistoryDOM.childNodes.length<=5) EmpryDOM.style.display="block";
		
	}
				
</script>
</html>